angular.module('purchasing-roles.controllers', [])

// 采购单列表
.controller('PurchaseOrderListCtrl', function($scope) {
	var purchaseSubHandle = $scope.subscribe('purchase');
	$scope.$on('$ionicView.enter', function(e) {
		var currUserDepts = Meteor.user().profile.departments;
		$scope.helpers({
			purchaseOrders: function() {
				return Purchase.find({'warehouse._id':currUserDepts[currUserDepts.length-1]._id,
					state:{'$nin':[0,1,5]}},{fields:{'total_cost':0,'paid':0}});
			}
		});
		$scope.stateUi = [
			{text:'作废',icon:'ion-ios-trash',color:'dark2'},
			{text:'采购计划',icon:'ion-ios-compose',color:'assertive'},
			{text:'已下单',icon:'ion-ios-list',color:'royal'},
			{text:'配送中',icon:'ion-plane',color:'royal'},
			{text:'已到货',icon:'ion-ios-home',color:'balanced'},
			{text:'已入库',icon:'ion-archive',color:'balanced'}];
		$scope.orderList=[];
		$scope.autorun(function(){
			if(purchaseSubHandle.ready() && $scope.purchaseOrders){  // && !$scope.purchaseOrders.loaded
				var today = moment().startOf('day').unix();

        $scope.purchaseOrders.forEach(function(order){
          var orderTime = moment(order.date).unix();
          // 距今天数
          var dayInx = Math.ceil((today-orderTime)/86400);
          // 为负数时则为日期为今天的
          dayInx = dayInx<=0?0:dayInx;
          if(!$scope.orderList[dayInx]) $scope.orderList[dayInx]={};

        　if (today<=orderTime) {
            if(!$scope.orderList[dayInx].divider) {
            	$scope.orderList[dayInx].divider = '今日';
            }
          }else {
          	if(today-orderTime<=86400){
            	if(!$scope.orderList[dayInx].divider) $scope.orderList[dayInx].divider = '昨日';
        	}else if((today-orderTime)/86400<=30){
	            if(!$scope.orderList[dayInx].divider) {
	            	$scope.orderList[dayInx].divider = moment(order.date).fromNow();
	            }
	        }else{
	            if(!$scope.orderList[dayInx].divider) {
	            	$scope.orderList[dayInx].divider = moment(order.date).format("YYYY-MM-DD");
	            }
	        }
	      }
          if(!$scope.orderList[dayInx].list) $scope.orderList[dayInx].list=[];

          $scope.orderList[dayInx].list.push(order);

        });
        //清除空元素
        for(var i = 0 ;i<$scope.orderList.length;i++){
          if($scope.orderList[i] === "" || typeof($scope.orderList[i]) == "undefined"){
            $scope.orderList.splice(i,1);
            i--;
          }
        }
			}
		});
	});
})

// 采购单详情
.controller('OrderDetailCtrl', function($scope,$rootScope,$state,$stateParams,$ionicPopup,PopupService,$ionicModal,$cordovaBarcodeScanner,ToastService) {
	var podSubHandle = $scope.subscribe('purchase');
	var productsSubHandle = $scope.subscribe('products');
	$scope.upState=[];

	// 产品条码
	$scope.barcodeList=[];
	$scope.$on('$ionicView.enter', function(e) {
		$scope.helpers({
			detail: function() {
				return Purchase.findOne({'_id':$stateParams._id},{fields:{'list.cost_price':0,'total_cost':0,'paid':0}});
			}
		});
		$scope.autorun(function(){
			if(podSubHandle.ready() && $scope.detail){
				for(var i=$scope.detail.state+1;i<5;i++){
					$scope.upState.push(i);
				}
				// 即将被改变到的状态
				$scope.toState={
					order_id: $scope.detail._id,
					state:{'operation':{}}
				};
				// 初始化库存数量
				$scope.detail.list.forEach(function(product){
					product.inventory_check=0;
					$scope.barcodeList.push(product.barcode);
				});

			}
		});
	});
	$scope.stateUi = [
		{note:'作废',icon:'ion-ios-trash',color:'dark2',bg:'dark2-bg'},
		{note:'采购计划',icon:'ion-ios-compose',color:'assertive',bg:'assertive-bg'},
		{note:'已下单',icon:'ion-ios-list',color:'royal',bg:'royal-bg'},
		{note:'配送中',icon:'ion-plane',color:'royal',bg:'royal-bg'},
		{note:'已到货',icon:'ion-ios-home',color:'balanced',bg:'balanced-bg'},
		{note:'已入库',icon:'ion-archive',color:'balanced',bg:'balanced-bg'}
	];

	$scope.isExpend = false;
	$scope.toggleHistory = function(item) {
		$scope.isExpend = !$scope.isExpend;
	};


	$scope.toggleProperty = function(item) {
		if ($scope.isItemShown(item)) {
		  $scope.shownItem = null;
		} else {
		  $scope.shownItem = item;
		}
	};
	$scope.isItemShown = function(item) {
		return $scope.shownItem === item;
	};


	$scope.updateState = function(){
		// 已作废，已入库不允许更改
		if($scope.detail.state===0 || $scope.detail.state===5) return;

		var myPopup = $ionicPopup.show({
			template: '<ion-list>'+
					    '<ion-radio ng-model="toState.state.operation.state" ng-value="{{theState}}" ng-repeat="theState in upState">{{stateUi[theState].note}}</ion-radio>'+
					  '</ion-list>',
			cssClass: 'popup-radio',
			title: '更新采购单状态',
			scope: $scope,
			buttons: [
				{ text: '取消' },
				{ text: '确定',type: 'button-royal',
					onTap: function(e) {
						$scope.toState.state.date=moment().toDate();
						$scope.toState.state.operation.note=$scope.stateUi[$scope.toState.state.operation.state].note;
						$scope.toState.state.operator={
			        		'_id':$rootScope.currentUser._id,
			        		'name':$rootScope.currentUser.profile.name
				        };

				        Meteor.call('updatePOState', $scope.toState, function(error){
							if (error) {

								PopupService.showAlert(error.reason);
							} else {
								ToastService.show('状态更新成功');
							}
						});
					}
				}
			]
		});
	};


	$ionicModal.fromTemplateUrl('templates/purchasing/stock-in.html', {
		scope: $scope,
		animation: 'slide-in-up'
	}).then(function(modal) {
		$scope.inventoryInModal = modal;
	});

	$scope.$on('$destroy', function() {
		$scope.inventoryInModal.remove();
	});

	$scope.scanBarcode = function() {
		$cordovaBarcodeScanner.scan().then(function(imageData) {
			var productFromBarcode = Products.find({barcode:imageData.text});
			if(!productFromBarcode){
				ToastService.show('未找到该商品，请先录入');
				$state.go('app.add-product');
			}else{
				var barcodeIndex = $scope.barcodeList.indexOf(imageData.text);
				if(barcodeIndex!=-1){
					$scope.detail.list[barcodeIndex-1].inventory_check++;
				}else{
					alert('该商品不在采购单中, 请单独入库');
				}
			}
		});
	};

	$scope.inventoryIn = function(){
		ToastService.show('入库完成');
		$state.go('app.purchase-order-list');
	};
})

.controller('CreatePurchasingOrderCtrl', function($scope,$rootScope,$state,$ionicModal,$ionicPopup,PopupService,$cordovaBarcodeScanner,COMMON_MSG) {
	var deptsSubHandle = $scope.subscribe('departments');
	var suppliersSubHandle = $scope.subscribe('suppliers');
	var productsSubHandle = $scope.subscribe('products');

	$scope.order={
		state : 2,
		warehouse:{},
		wh:{},  //临时
		total_count:0,
		total_cost:0,
		list:[]
	};

	$scope.$on('$ionicView.enter', function(e) {
		$scope.helpers({
			warehouses: function() {
				return Departments.find({'$and':[{state: '启用'},{'$or':[{type:'仓库'},{type:'柜组'}]}]});
			},
			suppliers: function() {
				return Suppliers.find({},{fields: {company:1}});
			},
			products: function() {
				return Products.find({});
			}
		});

		$scope.autorun(function(){
			if(productsSubHandle.ready() && $scope.products){ // && !$scope.products.loaded
				$scope.title = '全部商品';
				// 获取品牌列表
				$scope.brandList = {};
				$scope.products.forEach(function(product) {
					product.cost_price = product.cost_price_default;
					product.cost_price_default =undefined;
					if(!$scope.brandList[product.properties.brand.value]){
						$scope.brandList[product.properties.brand.value]=1;
					}else{
						$scope.brandList[product.properties.brand.value]+=1;
					}
					return;
				});
			}
			if(deptsSubHandle.ready() && $scope.warehouses){
				$scope.order.wh=$scope.warehouses[0];
			}
		});
	});
	$ionicModal.fromTemplateUrl('templates/supplier/select.html', {
		scope: $scope,
		animation: 'slide-in-up'
	}).then(function(modal) {
		$scope.supplierModal = modal;
	});


	$ionicModal.fromTemplateUrl('templates/product/select.html', {
		scope: $scope,
		animation: 'slide-in-up'
	}).then(function(modal) {
		$scope.productsModal = modal;
	});

	$scope.$on('$destroy', function() {
		$scope.supplierModal.remove();
		$scope.productsModal.remove();
	});
	$scope.stateUI=[{'state':1,'note':'采购计划'},{'state':2,'note':'已下单'}];


	$scope.scanBarcode = function() {
		$cordovaBarcodeScanner.scan().then(function(imageData) {
			var productFromBarcode = Products.find({barcode:imageData.text});
			if(!productFromBarcode){
				ToastService.show('未找到该商品，请先录入');
				$state.go('app.add-product');
			}
			var index = $scope.order.list.indexOf(productFromBarcode);
			if(index == -1){
				// 初始化数量
				productFromBarcode.count=1;
				$scope.order.total_count++;
				$scope.order.list.push(productFromBarcode);
			}else{
				$scope.order.list[index].count++;
			}
		}, function(error) {
			console.log("An error happened -> " + error);
		});
	};
	// 选择供应商
	$scope.selectSupplier=function(supplier){
		$scope.order.supplier = supplier;
		$scope.supplierModal.hide();
	};
	// 已选择的产品
	$scope.selectProduct = function(product){
		var index = $scope.order.list.indexOf(product);
		if(index == -1){
			// 初始化数量
			product.count=1;
			$scope.order.total_count++;
			$scope.order.list.push(product);
		}else{
			$scope.order.list.splice(index,1);
			$scope.order.total_count-=product.count;
		}
	};
	// 显隐分类
	$scope.toggleCat=function(){
		$scope.showCat = ! $scope.showCat;
	};
	// 显隐价格数量
	$scope.toggleItem = function(item) {
		if ($scope.isItemShown(item)) {
		  $scope.shownItem = null;
		} else {
		  $scope.shownItem = item;
		}
	};
	$scope.isItemShown = function(item) {
		return $scope.shownItem === item;
	};
	// 参数为引用传参
	$scope.minusCount = function(product){
		if(product.count>=2){
			product.count--;
			$scope.order.total_count--;
		}
	};
	$scope.addCount = function(product){
		product.count++;
		$scope.order.total_count++;
	};
	$scope.$watch('order.list', function(newValue, oldValue) {
		$scope.order.total_cost = 0;
	    angular.forEach(newValue, function(item, key) {
	    	// 数量不合法时强制改为1
	    	if(!item.count || item.count<1){
	    		item.count = 1;
	    	}
	    	$scope.order.total_cost+=item.cost_price * item.count;
	    });
	},true); //检查被监控的对象的每个属性是否发生变化


	$scope.finish = function(){
    	$scope.productsModal.hide();
	};

	$scope.create = function(){
		// console.log($scope.order);
		 if(!$scope.order.supplier){
				 PopupService.showAlert("请选择供应商");
        	return;
        }
        $scope.order.state_history=[{
        	'date':moment().toDate(),
        	'operation':$scope.stateUI[$scope.order.state-1],
        	'operator':{
        		'_id':$rootScope.currentUser._id,
        		'name':$rootScope.currentUser.profile.name
        	}
        }];
        $scope.order.state_history[0].operation.$$hashKey=undefined;

        $scope.order.warehouse._id=$scope.order.wh._id;
        $scope.order.warehouse.name=$scope.order.wh.name;
        $scope.order.wh=undefined;
        console.log($scope.order);
        if(!$scope.order.paid) $scope.order.paid=$scope.order.total_cost;


		Meteor.call('createPurchaseOrder', $scope.order, function(error){
			if (error) {
				PopupService.showAlert(error.reason);
			} else {
				$scope.productsModal.hide();
				$state.go('app.purchase');
			}
		});
	};
});
